#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include "log.hpp"
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>
int main(int argc,char* argv[]){
    if(argc != 3){
        std::cerr<<"Usage: "<<argv[0]<<"server_ip server_port"<<std::endl;
        return 1;
    }
    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);

    int sockfd = socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd < 0){
        std::cerr<<"socket error"<<std::endl;
        return 2;
    }
    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    if(inet_aton(server_ip.c_str(),&server.sin_addr) != 1){
        std::cerr<<"inet_aton error"<<std::endl;
        return 2;
    }
    server.sin_port = htons(server_port);
    server.sin_family = AF_INET;
    std::string input;
    std::cout<<"输入quit退出\n";
    do
    {
        std::cout<<"INPUT:";
        std::getline(std::cin,input);
        printf("###############\n");
        if(input.empty()){
            std::cout<<"非法输入，请重新输入\n";
            continue;
        }
        if(input != "quit"){
            sendto(sockfd,input.c_str(),input.size(),0,(struct sockaddr*)&server,sizeof(server));
            std::cout<<"sendto successfully"<<std::endl;
            char recieveBuffer[1024];
            struct sockaddr_in peer;
            socklen_t len;
            int n = recvfrom(sockfd
                    ,recieveBuffer
                    ,sizeof(recieveBuffer) - 1
                    ,0
                    ,(struct sockaddr*)&peer
                    ,&len);
            if(n < 0){
                std::cerr<<"recvfrom error"<<std::endl;
            }
            else{
                recieveBuffer[n]=0;
                std::cout<<"recvfrom sucessfully"<<std::endl;
                std::string serverIp;
                char replyBuffer[1024];
                if(inet_ntop(AF_INET,&peer.sin_addr,replyBuffer,sizeof(replyBuffer)) != nullptr){
                    serverIp = replyBuffer;
                }  
                std::cout<<"SERVER[" + serverIp + "]:" + recieveBuffer<<std::endl;
            }
        }
    } while (input != "quit");
    close(sockfd);    
    return 0;
}